/*//GEN-FIRST:event_tfSenhaActionPerformed
 * To change this template, choose Tools | Templates//GEN-LAST:event_tfSenhaActionPerformed
 * and open the template in the editor.
 */

/*
 * LoginGUI.java
 *
 * Created on 21/04/2011, 14:29:48
 */
package cliente.gui;

import java.awt.event.KeyEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import util.ProtocoloMensagem;
import util.VerificaLogin;

/**
 *
 * @author aers
 */
public class LoginGUI extends javax.swing.JFrame {

    public static final int PORTA = 6790;
    private util.ProtocoloMensagem protocolo;

    /** Creates new form LoginGUI */
    public LoginGUI() {
        protocolo = new ProtocoloMensagem();
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            
            this.setBounds(400, 200, 428, 300);
            initComponents();
               this.setLocationRelativeTo(null);
            tfHostname.setText("10.28.15.187");
           // tfMatricula.setText("08n10509");
            //tfSenha.setText("cl142536");
            tfSenha.grabFocus();
        } catch (Exception e) {
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        tfMatricula = new javax.swing.JTextField();
        bLogin = new javax.swing.JButton();
        bCadastrar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        tfSenha = new javax.swing.JPasswordField();
        jLabel4 = new javax.swing.JLabel();
        tfHostname = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Sistema de pergunas e respostas - Login");
        setBounds(new java.awt.Rectangle(0, 0, 0, 0));
        setResizable(false);

        jLabel1.setText("Matricula:");

        jLabel2.setText("Senha:");

        bLogin.setText("Login");
        bLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bLoginActionPerformed(evt);
            }
        });

        bCadastrar.setText("Cadastrar");
        bCadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bCadastrarActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 24));
        jLabel3.setText("Sistema de Perguntas e Respostas");

        tfSenha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfSenhaActionPerformed(evt);
            }
        });

        jLabel4.setText("Hostname:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(121, 121, 121)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(bLogin)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(tfHostname)
                            .addComponent(tfMatricula, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                            .addComponent(bCadastrar, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(tfSenha, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 126, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel3))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 428, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(51, 51, 51)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(tfHostname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfMatricula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tfSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bCadastrar)
                    .addComponent(bLogin))
                .addContainerGap(92, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void bLoginActionPerformed(java.awt.event.ActionEvent evt) {                                       
        try {
            Socket clientSocket;
            String hostname = tfHostname.getText();
            clientSocket = new Socket(hostname, LoginGUI.PORTA);
            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
            DataInputStream inFromServidor = new DataInputStream(clientSocket.getInputStream());
            outToServer.writeUTF(protocolo.codificarLoginUsuario(tfMatricula.getText(), VerificaLogin.gerarMD5(tfSenha.getText())));
            String[] recebido = protocolo.decodificar(inFromServidor.readUTF());
            if (recebido[0].equals("ERRO")) {
                String erro = recebido[1];
                JOptionPane.showMessageDialog(this, "Erro: " + erro);
            } else {
                /*Suceso*/
                /**Verificação para saber se é administrados*/
                if (recebido[2].equals("true")) {
                    //Chamar todos os metodos para usuario Admin
                    AdminGUI adminGui = new AdminGUI(tfMatricula.getText(), hostname, PORTA);
                    adminGui.setExtendedState(adminGui.MAXIMIZED_HORIZ);
                    adminGui.setVisible(true);
                    this.dispose();
                } else {
                    UsuarioGUI userGui = new UsuarioGUI(tfMatricula.getText(), hostname, PORTA);
                    userGui.setVisible(true);
                    this.dispose();
                }
            }
        } catch (java.net.ConnectException e) {
            JOptionPane.showMessageDialog(null, "Não foi possivel a Conexão com o Servidor");
            e.printStackTrace();
        } catch (Exception e) {
        }
    }                                      

    private void bCadastrarActionPerformed(java.awt.event.ActionEvent evt) {                                           
        if(tfHostname.getText().isEmpty())
            JOptionPane.showMessageDialog(this, "Hostname precisa ser definido antes");
        else {
            Cadastro cadastro = new Cadastro(tfHostname.getText(), PORTA);
            cadastro.setVisible(true);
        }
        
    }                                          

    private void tfSenhaActionPerformed(java.awt.event.ActionEvent evt) {                                        
        bLoginActionPerformed(evt);
    }                                       


    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new LoginGUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton bCadastrar;
    private javax.swing.JButton bLogin;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField tfHostname;
    private javax.swing.JTextField tfMatricula;
    private javax.swing.JPasswordField tfSenha;
    // End of variables declaration                   

    void setHostname(String hostname) {
        tfHostname.setText(hostname);
    }

    void setMatricula(String matricula) {
        tfMatricula.setText(matricula);
    }

    void setSenha(String senha) {
        tfSenha.setText(senha);
    }
}
